﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using brand.admin.cyt369.com.services.Models;
using System.Xml.Linq;

namespace brand.admin.cyt369.com.services.Services
{
    public class BrandService : admin.cyt369.com.services.ORM.BaseService<BrandService>
    {
        public BrandService() { }

        #region Brand


        /// <summary>
        /// 查询品牌信息
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public brand.admin.cyt369.com.services.Models.Brand GetBrandByID(long brandId)
        {
            using (var ctx = this.Ctx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.Category)
                             where o.Id == brandId && o.IsDeleted == false
                             select o).FirstOrDefault();

                return brand;
            }
        }

        /// <summary>
        /// 查询品牌信息（包含图片）
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public brand.admin.cyt369.com.services.Models.Brand GetBrandByID_IncludeImg(long brandId)
        {
            using (var ctx = this.Ctx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandImages).Include(c => c.Category)
                             where o.Id == brandId && o.IsDeleted == false
                             select o).FirstOrDefault();

                return brand;
            }
        }

        /// <summary>
        /// 查询品牌信息（包含图片,包含删除）
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public brand.admin.cyt369.com.services.Models.Brand GetBrandByID_IncludeImg_IncludeDel(long brandId)
        {
            using (var ctx = this.Ctx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandImages).Include(c => c.Category)
                             where o.Id == brandId
                             select o).FirstOrDefault();

                return brand;
            }
        }

        /// <summary>
        /// 获取商品扩展信息
        /// </summary>
        /// <param name="brandId"></param>
        /// <returns></returns>
        public brand.admin.cyt369.com.services.Models.BrandExtension GetBrandExtension(int brandId)
        {
            using (var ctx = this.Ctx)
            {
                var brandExtension = (from o in ctx.BrandExtensions
                                      where o.BrandID == brandId
                                      select o).FirstOrDefault();
                return brandExtension;
            }
        }
        /// <summary>
        /// 查询品牌审核结果_包含图片
        /// </summary>
        /// <param name="brandId"></param>
        /// <returns></returns>
        public IQueryable<brand.admin.cyt369.com.services.Models.Brand> GetBrandByReviewResult_IncludeImg(long reviewResult)
        {
            using (var ctx = this.Ctx)
            {
                var brand = from o in ctx.Brands.Include(c => c.Category).Include(c=>c.BrandImages)
                            where o.ReviewResult == reviewResult && o.IsDeleted == false
                            select o;
                return brand;
            }
        }

        /// <summary>
        /// 删除品牌
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool BrandDelete(long brandId)
        {
            using (var ctx = this.Ctx)
            {
                var brand = (from o in ctx.Brands.Include(c => c.BrandExtension).Include(c => c.BrandImages)
                                where o.Id == brandId
                                select o).FirstOrDefault();

                if (brand != null)
                {
                    //if (brand.InquiryCount > 0)
                    //{
                        brand.IsDeleted = true;
                        ctx.SaveChanges();
                    //}
                    //else
                    //{
                    //    #region 移除OSS上的文件
                    //    if (brand.BrandImages != null)
                    //    {
                    //        foreach (var files in brand.BrandImages)
                    //        {
                    //            try
                    //            {
                    //                if (!string.IsNullOrEmpty(files.ImagePath))
                    //                {
                    //                    Admin.CYT369.Com.Utility.OssClientService.Instance.RemoveFile(Admin.CYT369.Com.Utility.SystemSettingService.Instance.BrandInternalBucket, files.ImagePath);
                    //                }
                    //            }
                    //            catch { }
                    //        }
                    //    }
                    //  #endregion

                        //ctx.Brands.Remove(brand);
                        //ctx.SaveChanges();
                    //}

                    return true;
                }
            }

            return false;
        }


        /// <summary>
        /// 获取所有的品牌
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="total"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        public IQueryable<brand.admin.cyt369.com.services.Models.Brand> GetBrands(int page, int rows, ref int total,
                                                                                 int? status = null, string name = null,
                                                                                 int? year = null, int? month = null,
                                                                                 int? categoryID = null,bool isDeleted=false)
        {
            using (var BrandCtx=this.Ctx)
            {
                var items = BrandCtx.Brands
                    .Where(c=> c.IsDeleted == isDeleted);
                if (status.HasValue)
                {
                    items = items.Where(c => c.ReviewResult == status.Value);
                }

                if (year.HasValue)
                {
                    items = items.Where(c => c.CreateDate.Year == year.Value);
                }

                if (month.HasValue)
                {
                    items = items.Where(c => c.CreateDate.Month == month.Value);
                }

                if (categoryID.HasValue)
                {
                    items = items.Where(i=>i.CategoryID==categoryID);
                }

                if (!string.IsNullOrEmpty(name))
                {
                    items = items.Where(c => c.Name.Contains(name));
                }

                return items = this.Pagination(page, rows, ref total, items, c => c.Id).ToList().AsQueryable();
            }
        }

        /// <summary>
        /// 获取品牌图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IQueryable<BrandImage> GetBrandImagesByBrandID(int id)
        {
            using (var BrandCtx = this.Ctx)
            {
                var items = BrandCtx.BrandImages
                    .Where(c => c.BrandID==id);

                return items.ToList().AsQueryable();
            }
        }

       
        /// <summary>
        /// 获取品牌记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IQueryable<BrandReview> GetBrandReviewsByBrandID(int id)
        {
            using (var BrandCtx = this.Ctx)
            {
                var items = BrandCtx.BrandReviews
                    .Where(c => c.BrandID == id);

                return items.ToList().AsQueryable();
            }
        }


        /// <summary>
        /// 获取品牌统计
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public brand.admin.cyt369.com.services.Models.BrandStastics GetBrandStastics(long userId)
        {
            var items = base.Get<brand.admin.cyt369.com.services.Models.Brand>(c => c.EditorID == userId);

            var stastics = new brand.admin.cyt369.com.services.Models.BrandStastics()
            {
                Total = items.Where(c => c.IsDeleted == false).Count(),
                PassedAudit = items.Where(c => c.IsDeleted == false && c.ReviewResult == 1).Count(),
                FailedAudit = items.Where(c => c.IsDeleted == false && c.ReviewResult == -1).Count(),
                AwaitAudit = items.Where(c => c.IsDeleted == false && c.ReviewResult == 0).Count(),
                Draft = items.Where(c => c.IsDeleted == false && c.ReviewResult == -2).Count(),
                YearGroup = (from o in items
                             group o by o.CreateDate.Year into go
                             select go.Key).ToArray(),

                MonthGroup = (from o in items
                              group o by o.CreateDate.Month into go
                              select go.Key).ToArray()
            };

            return stastics;
        }
        #endregion

        /// <summary>
        /// 获取类别 通过父级ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IQueryable<brand.admin.cyt369.com.services.Models.Category> CategorysGetByParentID(int id)
        {
                var categorys =base.Get<brand.admin.cyt369.com.services.Models.Category>().Where(c=>c.ParentID==id);
                return categorys;
        }


        /// <summary>
        /// 执行审核
        /// </summary>
        /// <param name="brandId"></param>
        /// <param name="auditStatusId"></param>
        /// <param name="auditUserId"></param>
        /// <param name="auditRemark"></param>
        /// <returns></returns>
        public bool DoBrandAudit(long brandId, int reviewResult, int auditUserId,string reviewerName, string reviewRemark)
        {
            using (var db = this.Ctx)
            {
                var brand = (from o in db.Set<brand.admin.cyt369.com.services.Models.Brand>()
                           where o.Id == brandId
                           select o).FirstOrDefault();

                if (brand != null)
                {
                    brand.ReviewResult = reviewResult;

                    db.BrandReviews.Add(new brand.admin.cyt369.com.services.Models.BrandReview()
                    {
                        BrandID = brand.Id,
                        ReviewResult = reviewResult,
                        ReviewerID = auditUserId,
                        ReviewerName= reviewerName,
                        ReviewRemark = reviewRemark,
                        ReviewDate = DateTime.Now
                    });

                    db.SaveChanges();

                    return true;
                }
            }

            return false;
        }
    }
}
